
'use strict';

const glob = require('glob');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin');
const FriendlyErrorsWebpackPlugin =  require('friendly-errors-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');




// 多页页面应用
const setMAP = () => {
	const entry = {};
	const HtmlWebpackPlugins = [];
	const entryFiles = glob.sync(path.join(__dirname, './src/*/*.js'));
	Object.keys(entryFiles).map((index) => {
		const entryFile = entryFiles[index];
		const match = entryFile.match(/src\/(.*)\/index\.js/);
		if (match) {
			const pageName = match && match[1];
			entry[pageName] = entryFile;
			HtmlWebpackPlugins.push(
				new HtmlWebpackPlugin({
					title:'search',
					template: path.resolve(__dirname, `src/${pageName}/index.template.html`),
					hash: false,
					filename: `${pageName}.html`,
					inject: true,
					// chunks: ['vendors',pageName],
					chunks: [pageName],
					minify: {
						html5:true,
						collapseWhitespace: true,
						preserveLineBreaks:true,
						minifyCSS:true,
						minifyJS:true,
						removeComments: true,
						removeAttributeQuotes: true
					}
				})
			)
		}

	});


	return {
		entry,
		HtmlWebpackPlugins
	}
};

const {entry,HtmlWebpackPlugins } = setMAP();

module.exports = {
	entry: entry,
	output: {
		path: path.join(__dirname, 'dist'),
		filename: "js/[name]_[chunkhash:8].js"
	},
	mode: "production",
	module: {
		rules: [
			{
				test: /.js$/,
				use: ['babel-loader', 'eslint-loader']
			},
			{
				test: /.css$/,
				use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
			},
			{
				test: /.less$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'less-loader',
					'postcss-loader',
					{ // px 转rem
						loader: 'px2rem-loader',
						options: {
							remUni: 75, // 是以750的设计稿设计的  1rem => 75px
							remPrecision: 8 // px转换成rem的小数点的位数
						}
					},
				]
			},
			{
				test: /\.(png|svg|kpg|gif|jpeg|jpg)$/,
				use: [{
					loader: "url-loader",
					options: {
						limit:10240,
						name:'images/[name]_[hash:8].[ext]'
					}
				}]
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: [{
					loader: "file-loader",
					options: {
						name:'fonts/[name]_[hash:8].[ext]'
					}
				}]
			}
		]
	},
	plugins: [
		new CleanWebpackPlugin(),
		new MiniCssExtractPlugin({
			filename: 'css/[name]_[contenthash:8].css'
		}),
		// 压缩css
		new OptimizeCssAssetsPlugin({
			assetNameRegExp: /\.css$/g,
			cssProcessor: require('cssnano'),
		}),
		new FriendlyErrorsWebpackPlugin(),
		// new HtmlWebpackExternalsPlugin({
		// 	externals: [
		// 		{
		// 			module: 'react',
		// 			entry: "https://unpkg.com/react@16/umd/react.production.min.js",
		// 			global: 'React',
		// 		},
		// 	],
		// }),
		// new HtmlWebpackExternalsPlugin({
		// 	externals: [
		// 		{
		// 			module: 'react-dom',
		// 			entry: 'https://unpkg.com/react-dom@16/umd/react-dom.production.min.js',
		// 			global: 'ReactDOM',
		// 		},
		// 	],
		// })

		function () {
			this.hooks.done.tap('done', stats => {
				if (stats.compilation.errors && process.argv.indexOf('--watch') == -1) {
					console.log('build err')
					process.exit(1)
				}
			})
		}
	].concat(HtmlWebpackPlugins),
	optimization:{
		splitChunks:{
			chunks: "all",
			minSize: 30000,
			maxSize: 0,
			minChunks: 1,
			maxAsyncRequests: 5,
			maxInitialRequests:3,
			automaticNameDelimiter: '--', // 分包打包生成文件的名称的连接符
			cacheGroups:{
				// commons:{
				// 	test: /(react|react-dom)/,
				// 	name:'vendors',
				// 	chunks: "all",
				// },
				commons:{
					name:'commons',
					chunks: "all",
					minChunks: 2
				}
			}
		}
	},
	stats: "errors-only"
};
